// 认证中间件
import jwt from 'jsonwebtoken';
import type { FastifyRequest, FastifyReply } from 'fastify';
import { errorResponse } from '../utils/response.ts';

// 定义用户类型
interface User {
  id: string;
  username: string;
  [key: string]: any;
}

// 扩展 Fastify 类型
declare module 'fastify' {
  interface FastifyRequest {
    user?: User;
  }
  
  interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<FastifyReply | void>;
  }
}

/**
 * 认证中间件函数
 * 验证用户请求中的JWT令牌，确保用户已登录
 * @param {FastifyRequest} request - Fastify请求对象
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply | void>} 如果认证失败则返回错误响应，否则无返回值
 */
export async function authenticate(request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply | void> {
  try {
    // 从Authorization头部获取令牌
    const authHeader = request.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return reply.code(401).send({
        code: 401,
        success: false,
        message: '用户未登录',
        data: {}
      });
    }
    
    // 提取令牌（移除'Bearer '前缀）
    const token = authHeader.substring(7);
    
    // 验证令牌
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'secret') as User;
    
    // 将用户信息添加到请求对象中
    request.user = decoded;
  } catch (error) {
    return reply.code(401).send(errorResponse('无效的认证令牌', 401));
  }
}
